package edu.luc.cs413s13.team1.monsterm.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import edu.luc.cs413s13.team1.monsterm.controller.R;
import edu.luc.cs413s13.team1.monsterm.model.MonstermModel;
import edu.luc.cs413s13.team1.monsterm.model.cell.Cell;
import edu.luc.cs413s13.team1.monsterm.model.common.Constants;
import edu.luc.cs413s13.team1.monsterm.model.monster.Monster;

public class DefaultMonstermView extends View {
	Context context;
	MonstermModel model;
	Paint paint;
	Bitmap bitmap;
	int cellSize;
	int displayHeight;
	int displayWidth;
	int gridWidth;
	int gridHeight;
	
	public DefaultMonstermView(Context context, AttributeSet attributes) {
		super(context, attributes);
		this.context = context;
		paint = new Paint();
		paint.setColor(Color.BLACK);
        paint.setStrokeWidth(1);
        paint.setStyle(Style.STROKE);
		displayHeight = context.getResources().getDisplayMetrics().heightPixels;
		displayWidth = context.getResources().getDisplayMetrics().widthPixels;
		gridWidth = displayWidth / Constants.CELL_SIZE;
		gridHeight = (displayHeight - Constants.VIEW_HEIGHT_MINUS) / Constants.CELL_SIZE;
		
	}
	
	
	@Override
	protected void onDraw(Canvas canvas) {
        Cell[][] grid = model.getWorld().getGrid();
        for (int i = 0; i < gridWidth; i += 1) {
        	for (int j = 0; j < gridHeight; j += 1) {
        		Cell cell = grid[i][j]; 
        		if(cell.getOccupants().size() > 0) {
        			Log.i(Constants.TAG, "Actors count: " + cell.getOccupants().size());
        			
        			if (cell.getOccupants().size() <= 0) return;
        			
                    Monster m = (Monster)cell.getOccupants().get(0);
                    if (m.isProtected()) {
                    	bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.gmonster);
                    } else {
                    	bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ymonster);                    	
                    }
                    canvas.drawBitmap(bitmap, i * cellSize, j * cellSize, paint);
        		}
        		/*canvas.drawRect(i * cellSize, 
        				j * cellSize, 
        				i * cellSize + cellSize, 
        				j * cellSize + cellSize, 
        				paint);*/
            }
        }
        paint.setTextSize(20);
        canvas.drawText ("Current Score: " + model.getScore(), 
        		displayWidth/2-60, displayHeight-160, paint);

	}
	
	public void setModel(MonstermModel model) { this.model = model; }
	
	public void init(Cell[][] cells, int cellSize) {
	    gridWidth = cells.length;
	    gridHeight = cells[0].length;
	    this.cellSize = cellSize;   
	}

}
